import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { PointsLogEntity } from './points-log.entity';
import { Repository, DataSource } from 'typeorm';
import { Pagination } from '~/helper/paginate/pagination';
import { FindPointsLogsListDto } from './points-log.dto';
import { paginate } from '~/helper/paginate';
import { CommonStatus } from '~/common/entity/common.entity';
import { isNil } from 'lodash';
import { UserEntity } from '~/modules/user/user.entity';
import { UserWechatEntity } from '~/modules/user/user-wechat/user-wechat.entity';
import { ArticleContentEntity } from '~/modules/article/article-content/article-content.entity';
import { SurveyEntity } from '~/modules/survey/survey.entity';

@Injectable()
export class PointsLogService {
  constructor(
    @InjectRepository(PointsLogEntity)
    private readonly pointsLogRepository: Repository<PointsLogEntity>,
    @InjectDataSource()
    private readonly dataSource: DataSource
  ) {}

  async create(pointsLog: Partial<PointsLogEntity>, userId: number): Promise<PointsLogEntity> {
    return await this.pointsLogRepository.save({ ...pointsLog, user: { id: userId } });
  }

  async findByList({
    userId,
    page,
    pageSize,
  }: FindPointsLogsListDto & { userId: number }): Promise<Pagination<PointsLogEntity>> {
    const queryBuilder = await this.pointsLogRepository
      .createQueryBuilder('ah_points_log')
      .where({
        user: { id: userId },
      })
      .orderBy('ah_points_log.createdAt', 'DESC');

    return paginate<PointsLogEntity>(queryBuilder, {
      page,
      pageSize,
    });
  }

  async countByUserId(userId: number): Promise<number> {
    if (isNil(userId)) {
      return 0; // 如果用户ID为空，直接返回0
    }

    const result = await this.pointsLogRepository
      .createQueryBuilder('ah_points_log')
      .select('SUM(ah_points_log.points)', 'total') // 统计积分总和
      .where('ah_points_log.userId = :userId', { userId }) // 根据用户ID过滤
      .where('ah_points_log.pointsType = :pointsType', { pointsType: CommonStatus.YES })
      .getRawOne();

    return result.total ? Number(result.total) : 0; // 返回总和，如果为空则返回0
  }

  /**
   * 获取所有积分日志
   * @returns 积分日志列表
   */
  async getAllPointsLogs(): Promise<Partial<PointsLogEntity>[]> {
    return await this.dataSource
      .createQueryBuilder()
      .select('points_log.id', 'id')
      .addSelect('points_log.created_at', 'createdAt')
      .addSelect('points_log.title', 'title')
      .addSelect('points_log.points', 'points')
      .addSelect('points_log.userId', 'userId')
      .addSelect('points_log.pointsType', 'type')
      .addSelect("TRIM(REPLACE(REPLACE(points_log.mission_type, '\r', ''), '\n', ''))", 'missionType')
      .addSelect('points_log.mission_related_data', 'missionRelatedData')
      .addSelect('userWechat.nickname', 'nickname')
      .addSelect('userWechat.phone', 'phone')
      .addSelect('article.code', 'articleCode')
      .addSelect('article.name', 'articleName')
      .addSelect('survey.name', 'surveyName')
      .from(PointsLogEntity, 'points_log')
      .leftJoin(UserEntity, 'user', 'user.id = points_log.userId')
      .leftJoin(UserWechatEntity, 'userWechat', 'userWechat.id = user.wechat_id')
      .leftJoin(
        ArticleContentEntity,
        'article',
        `article.id = CAST(points_log.mission_related_data AS UNSIGNED)`
      )
      .leftJoin(
        SurveyEntity,
        'survey',
        `survey.page_id = points_log.mission_related_data`
        // `(points_log.mission_type = 'QNAIRE' AND survey.page_id = points_log.mission_related_data) OR
   			// (points_log.mission_type = 'EXAM' AND survey.page_id = points_log.mission_related_data)`
      )
      .getRawMany();
  }
}
